import React from 'react';
import type {ModalFormProps} from '@ant-design/pro-components';
import {ModalForm, ProFormText} from '@ant-design/pro-components';
import {message} from 'antd';

export type ConfirmPasswordModalProps = {
  // 自定义 Modal 标题
  title?: string;
  // 自定义确认按钮文本
  okText?: string;
  // 自定义取消按钮文本
  cancelText?: string;
  // 自定义密码输入框的 label
  passwordLabel?: string;
  // 自定义密码输入框的 placeholder
  passwordPlaceholder?: string;
  // 触发元素
  trigger?: JSX.Element;
  // Modal 的其他属性
  modalProps?: ModalFormProps;
  // 提交方法，返回 Promise<boolean> 表示是否提交成功
  onSubmit?: (password: string) => Promise<boolean>;
  // 子元素，作为 trigger 的替代方案
  children?: React.ReactNode;
};

const ConfirmPasswordModal: React.FC<ConfirmPasswordModalProps> = (props) => {
  const {
    title = '确认密码',
    okText = '确认',
    cancelText = '取消',
    passwordLabel = '请输入密码',
    passwordPlaceholder = '请输入您的密码',
    trigger,
    children,
    modalProps = {},
    onSubmit,
  } = props;

  return (
    <ModalForm
      title={title}
      trigger={trigger || children as any}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        ...modalProps.modalProps,
      }}
      width={modalProps.width || 400}
      submitTimeout={2000}
      onFinish={async (values) => {
        if (onSubmit) {
          try {
            return await onSubmit(values.password);
          } catch (error) {
            message.error('操作失败');
            return false;
          }
        }
        return false;
      }}
      {...modalProps}
    >
      <ProFormText.Password
        name="password"
        label={passwordLabel}
        placeholder={passwordPlaceholder}
        rules={[
          {
            required: true,
            message: '请输入密码',
          },
        ]}
      />
    </ModalForm>
  );
};

export default ConfirmPasswordModal;
